package com.kos.snakerunningsystem.service.impl.utils;

import com.kos.snakerunningsystem.util.SnakeInterface;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Component
public class Consumer extends Thread {
    private Snake snake;
    private static RestTemplate restTemplate;

    private static final String receiveSnakeMoveUrl = "http://127.0.0.1:8090/pk/receive/snake/move";

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        Consumer.restTemplate = restTemplate;
    }

    public void startTimeout(long timeout, Snake snake){
        this.snake = snake;
        this.start();

        try {
            //最多等待timeout秒
            this.join(timeout);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //中断当前线程
            this.interrupt();
        }
    }

    //在Snake类名后面加上uid，保证类名不一样
    private String addUid(String code, String uid){
        int k = code.indexOf(" implements com.kos.snakerunningsystem.util.SnakeInterface");
        return code.substring(0,k) + uid + code.substring(k);
    }

    @Override
    public void run() {
        UUID uuid = UUID.randomUUID();
        String uid = uuid.toString().substring(0,8);

        SnakeInterface snakeInterface = Reflect.compile("com.kos.snakerunningsystem.util.Snake" + uid, addUid(snake.getSnakeCode(),uid)).create().get();

        Integer direction = snakeInterface.nextMove(snake.getInput());

        System.out.println("move：" + snake.getUserId() + " " + direction);

        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("user_id",snake.getUserId().toString());
        data.add("direction",direction.toString());
        restTemplate.postForObject(receiveSnakeMoveUrl,data,String.class);
    }
}
